package com.eazy.lkv2.web.controller.system;


import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.eazy.lkv2.core.db.ZQ;
import com.eazy.lkv2.core.web.utils.AddrUtils;
import com.eazy.lkv2.core.web.utils.MD5;
import com.eazy.lkv2.core.web.utils.StrKit;
import com.eazy.lkv2.web.controller.BaseController;
import com.eazy.lkv2.web.entity.City;
import com.eazy.lkv2.web.entity.LoginLog;
import com.eazy.lkv2.web.service.system.count.BaiduService;
import com.eazy.lkv2.web.service.traffic.CityService;

/**
 * @author jzx
 * @desc 登录管理
 * @date 2016.06.16
 */
@Controller
@RequestMapping("/sys")
public class SystemLoginController extends BaseController<Object,Integer> {
	
	@Autowired
	private BaiduService baiduService;
	@Autowired
	private CityService cityService;
	
	// 由于时间关系，部分都用ZQ操作了，风格没有统一，抱歉了各位。
	//@Autowired
	//private WeatherService weatherService;
	
	// 2016-08-05 新加入
	//@Autowired
	//private WeatherAnalysis weatherAnalysis;
	
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = { RequestMethod.POST})
	public String login(RedirectAttributes flash) {
		Map<String, String>  map = getPageData(request);

		if(StrKit.isEmpty(map.get("name")) && StrKit.isEmpty(map.get("pwd")) ) {
			flash.addFlashAttribute("msg", "用户名和密码不能为空");
		}
		else if(StrKit.isEmpty(map.get("name"))) {
			flash.addFlashAttribute("msg", "用户名不能为空");
		}
		else if(StrKit.isEmpty(map.get("pwd"))) {
			flash.addFlashAttribute("msg", "密码不能为空");
		} 
		 else {
			// 需要的时候再去拿session
			String code = getAttrSessionToStr("code");

			if (!code.equalsIgnoreCase(map.get("code"))) {
				flash.addFlashAttribute("msg", "验证码输入错误");
			} else {
				try {
					UsernamePasswordToken token = new UsernamePasswordToken(map.get("name"),MD5.encodeString(map.get("pwd")));
					token.setRememberMe(true);
					Subject currentUser = SecurityUtils.getSubject();
					currentUser.login(token);
					// 验证是否登录成功
					if (currentUser.isAuthenticated()) {
						// 删除产生的废弃验证码
						removeAttrSession(map.get("code"));
						
						// 加入一些小功能 2016-07-14 实现百度地图统计的
						
						// 改进意见，底层mybatis 封装的不太好，如果不想添加某些字段报错太恶心了实在是
						String ipAddr = getIpAddr();
						
						if(!ipAddr.equals("0:0:0:0:0:0:0:1")) {
							//BaseData baseDat = weatherAnalysis.take("weather");
							JSONObject data = AddrUtils.requestGet(AddrUtils.LOCATION + ipAddr);
							
							LoginLog login_log = new LoginLog();
							
							login_log.setAccount(getCurrentUser().getName());
							login_log.setLoginIp(getIpAddr());
							login_log.setLoginTime(getSysTimestamp());
							login_log.setDetailAddress(data.getString("address"));
							
							JSONObject contentJsonObject = data.getJSONObject("content");
							 if (contentJsonObject != null) {
								 login_log.setAddress(contentJsonObject.getString("address"));
								 JSONObject point = contentJsonObject.getJSONObject("point");
								 if (point != null) {
									 login_log.setPointX(point.getBigDecimal("x"));
									 login_log.setPointY(point.getBigDecimal("y"));
	                             }
								 JSONObject address_detailJsonObject = contentJsonObject.getJSONObject("address_detail");
	                             if (address_detailJsonObject != null) {
	                            	 login_log.setProvince(address_detailJsonObject.getString("province"));
	                            	 login_log.setCity(address_detailJsonObject.getString("city"));
	                            	 login_log.setCityCode(address_detailJsonObject.getString("city_code"));
	                            	 
	                            	 // 2016-7-21 增加城市添加功能
	                            	 // 之前想用定时任务来写个爬虫来抓取数据，后来想想既然开源就不弄了
	                            	 if(!login_log.getCity().equals("")) {
	                            		 List<City> cityArray = cityService.queryByObject(new City(login_log.getCity()));
	                            		 
	                            		 // 由于天气api 限制了每天的访问数量
	                            		 JSONObject weatherData = getWeather(login_log.getCity());
	                            		 setAttrSession(ipAddr, weatherData);
	                            		 if (weatherData != null) {
		                            		 // 存放临时变量
	                            			 String weather = weatherData.getString("weather");
	                            			 String temperature = weatherData.getString("temperature");
	                            			 String nightPictureUrl = weatherData.getString("nightPictureUrl");
	                            			 String dayPictureUrl = weatherData.getString("dayPictureUrl");
	                            			 String wind = weatherData.getString("wind");
	                            			 
		                            		 if(cityArray.isEmpty()) {
		                            			 // 没有查到该城市信息，那么就添加好了
		                            			 City city = new City();
		                            			 city.setName(login_log.getCity());
		                            			 city.setStatus("0");
		                            			 Integer pK = cityService.create(city); // 返回添加ID
		                            			 ZQ.commonInsert("insert into weather(cityid,weather,temperature,nightPictureUrl,dayPictureUrl,wind) values(?,?,?,?,?,?)"
		                            					 ,new Object[]{pK,weather,temperature,nightPictureUrl,dayPictureUrl,wind});
		                            		 } else {
		                            			 // 不空的直接更新天气表数据（也就是说只能根据控制当前用户所在城市天气的更改，定时请求所有城市的话有限制）
		                            			 ZQ.commonUpdate("update weather set weather=?,wind=?,temperature=?,nightPictureUrl=?,dayPictureUrl=? where cityid=?", new Object[]{
		                            					 weather, wind,temperature,nightPictureUrl,dayPictureUrl,cityArray.get(0).getId()
		                            			 });
		                            		 }
	                            		 }
	                            	 }
	                             }
							 }
							baiduService.create(login_log);
						}
						return "redirect:/system/login";
					} else {
						token.clear();
					}
				} catch (AuthenticationException ex) {
					flash.addFlashAttribute("msg", "用户名或者密码输入错误!!!");
				}
			}
		}
		return "redirect:login";
	}
	
	/**
	 * 用户登出
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "system/login";
	}
	
	/**
	 * 登录失败
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String fail(ModelMap model)  {
		return "system/login";
	}
	
}
